import axios from 'axios'
import { message } from 'ant-design-vue'
import { useUserStore } from './stores/user'

const ElMessage = (_opt = {}) => {
  return message[_opt.type || 'info'](_opt?.message)
}
/**
 * @description 创建请求实例
 */
function createService() {
  // 创建一个 axios 实例
  const service = axios.create({
    timeout: 1000 * 60 * 5,
    baseURL: '/gc'
  })

  // 请求拦截
  service.interceptors.request.use(
    (config) => {
      if (!config.passAuth) {
        const userStore = useUserStore()
        config.auth = {
          username: userStore.userInfo.username,
          password: userStore.userInfo.token
        }
      }
      return config
    },
    (error) => {
      // 发送失败
      console.log(error)
      return Promise.reject(error)
    }
  )
  // 响应拦截
  service.interceptors.response.use(
    (res) => {
      const response = res?.data || {}
      if (response?.code !== 1 && !res.config.noErrorTips) {
        ElMessage({
          message: response.message,
          type: 'error'
        })
        return Promise.reject(response)
      }

      if (res.config.responseType === 'blob') {
        return response
      }
      if (res.config.unpack) {
        return response
      }
      return response.data
    },
    (error) => {
      const status = error.response?.status
      if (error?.config?.noHandleError) {
        return Promise.reject(error)
      }
      switch (status) {
        case 400:
          ElMessage({
            message:
              'The client sent an invalid request, such as missing required request body or parameters.',
            type: 'error'
          })
          break
        case 401:
          ElMessage({
            message: '请重新登录.',
            type: 'error'
          })
          location.href = `${window.location.origin}${location.pathname}#/login`
          break
        case 403:
          ElMessage({
            message:
              'The client is authenticated but does not have permission to access the requested resource.',
            type: 'error'
          })
          break
        case 404:
          ElMessage({
            message: 'The requested resource does not exist.',
            type: 'error'
          })
          break
        case 412:
          ElMessage({
            message: 'One or more conditions in the request header fields evaluate to false.',
            type: 'error'
          })
          break
        case 500:
          ElMessage({
            message: 'The server encountered a general error.',
            type: 'error'
          })
          break
        case 503:
          ElMessage({
            message: 'The requested service is unavailable.',
            type: 'error'
          })
          break
        default:
          ElMessage({
            message: 'Unknown error.',
            type: 'error'
          })
          break
      }
      return Promise.reject(error)
    }
  )
  return service
}

// 用于真实网络请求的实例和请求方法
export default createService()
